package com.UnionPayCenter.scheduler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.UnionPayCenter.constant.CouponConstants;
import com.UnionPayCenter.entity.vo.ExpiringUserCouponVo;
import com.UnionPayCenter.operation.entity.request.MpPushRequest;
import com.UnionPayCenter.service.ICouponService;
import com.UnionPayCenter.service.IWechatService;
import com.UnionPayCenter.util.DateFormatUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description： 优惠券定时任务
 * @author BaoJF
 *
 */
@Component
@Slf4j
public class CouponScheduleTasks {
    
    @Autowired
    private ICouponService couponService;
    
    @Autowired
    private IWechatService wechatService;

    /**
     * 每天10点发消息提醒用户3天内将过期的优惠券张数
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void pushCouponExpiringMsg() {
        log.info("开始扫描三天内过期的优惠券...");
        Date today = DateFormatUtil.getTodayStartTime(new Date());
        String expireDate = DateFormatUtil.dateToDayString(DateFormatUtil.dayCalculate(today, 3));
        log.info("过期日期:" + expireDate);
        
        List<ExpiringUserCouponVo> list = couponService.getExpiringUserCoupon(expireDate);
        for (ExpiringUserCouponVo expiringVo : list) {
            List<Integer> userIds = new ArrayList<Integer>();
            userIds.add(expiringVo.getUserId());
            
            MpPushRequest pushRequest = new MpPushRequest();
            pushRequest.setShopId(expiringVo.getShopId());
            pushRequest.setUserIds(userIds);
            pushRequest.setIndexPageId(CouponConstants.MSG_SHOW_PAGE_INDEX);
            pushRequest.setMessage(String.format(CouponConstants.EXPIRING_COUPON_MSG, expiringVo.getCount()));
            wechatService.pushMpMsg(pushRequest);
        }
        log.info("即将过期优惠券消息推送完成...");
    }
    
}
